<?php
defined('SYSPATH') or die('No direct script access.');

class Controller_Articles extends Controller_Initialize {

  public $secure_actions = array(
      // user actions
      'add' => 'admin',
      'my' => 'admin',
      'edit' => 'admin',
      'delete' => 'admin',
      'delete_tag' => 'admin',
      );


    public function action_index($url = null) {

      $this->template->navigation->active = 'articles';
     
      $articles = ORM::factory('article')->where('published', '!=', null)->find_all();
      $this->template->content = View::factory('templates/articles/index')
              ->bind('articles', $articles);    
   
    }

    public function action_view($url) {

      $this->template->navigation->active = 'articles';

      $id = explode("-", $url);
      $article = ORM::factory('article', $id[0]);
      $comments_article = ORM::factory('comments_article')->where('article_id', '=', $id[0])->find_all();
      $this->template->content = View::factory('templates/articles/view')
              ->bind('article', $article)
              ->bind('comments_article', $comments_article);

    }

    public function action_add() {

      $this->template->navigation->active = 'articles';
      $art_cat = ORM::factory('articles_category')->find_all();
      
      $view = View::factory('templates/articles/add')
                ->bind('art_cat', $art_cat);

      if (!empty($_POST)) {

        $articles = null;
        $articles = ORM::factory('article');
        $post = $articles->validate_add_article($_POST);
        $time = time();
        $upload_valid = true;

        if(! isset($_POST['article_tags'])) {
          $post['article_tags'] = array();
        }
        
          if ($_FILES['filedata']['size'] > 0) {
            $files = Validate::factory($_FILES)
            ->rules('filedata', array(
            'Upload::not_empty' => array(),
            'Upload::valid' => array(),            
            'Upload::type' => array('Upload::type' => array('jpg')),
            'Upload::size' => array('250K'))
            );

            if($files->check()) {
              $filename = upload::save($_FILES['filedata'],NULL, DOCROOT.'/temp');

              Image::factory($filename)
              ->resize(440, Image::WIDTH)
              ->save(DOCROOT.'files/articles/'.$time.'.jpg');

              unlink($filename);
              $articles->preview_image = 1;
              $upload_valid = true;
            } else {
              Message::add('warning', '<strong>Úvodní fotografie ke článku není validní.</strong> ');
              $upload_valid = false;
            }
          }
        if ($post->check() && $upload_valid) {

          $articles->username = $this->userAuth->username;
          $articles->title = $post['title'];
          $articles->seo_title = $post['seo_title'];
          $articles->text = $post['text'];
          $articles->date = $time;
          $articles->save();

          foreach (array_unique($post['categories']) as $item) {
            $articles_category = ORM::factory('articles_category', $item);
            $articles->add('articles_category', $articles_category);
            $articles_category->clear();
          }

          foreach (array_unique($post['article_tags']) as $item) {
            $model = ORM::factory('articles_tag')->where('tag', '=', $item)->find();

            if ($model->id) {
              $articles->add('articles_tag', $model);
            } else {
              $article_tags = ORM::factory('articles_tag');
              $article_tags->tag = $item;
              $article_tags->save();
              $articles->add('articles_tag', $article_tags);
              $article_tags->clear();
            }
          }
          
          if ($articles->saved()) {
            Message::add('success', 'Článek byl odeslán ke schválení.');
            Request::instance()->redirect('articles');
          }

        } else {
                    
          $view->set('dataPost', $_POST);
          $informations = null;

          foreach($post->errors('articles') as $item) {
            $informations .= '<span>'.$item.'</span>';
          }
          Message::add('warning', '<strong>Článek nebyl odeslán.</strong> '.$informations);
        }
      }
      
      $this->template->content = $view;

    }

    public function action_edit_add($id) {

      $this->template->navigation->active = 'articles';
      $art_cat = ORM::factory('articles_category')->find_all();

      $view = View::factory('templates/articles/edit')
                ->bind('art_cat', $art_cat);

      if (!empty($_POST)) {

        $articles = null;
        if (Auth::instance()->logged_in('admin')) {
          $articles = ORM::factory('article', $id);
        } else {
          $articles = ORM::factory('article', $id)->where('username', '=', $this->userAuth->username);
        }
        $view->set('articles', $articles);
        $post = $articles->validate_add_article($_POST);
        $upload_valid = true;

          if ($_FILES['filedata']['size'] > 0) {
            $files = Validate::factory($_FILES)
            ->rules('filedata', array(
            'Upload::not_empty' => array(),
            'Upload::valid' => array(),
            'Upload::type' => array('Upload::type' => array('jpg')),
            'Upload::size' => array('250K'))
            );

            if($files->check()) {
              $filename = upload::save($_FILES['filedata'],NULL, DOCROOT.'/temp');

              Image::factory($filename)
              ->resize(440, NULL)
              ->save(DOCROOT.'files/articles/'.$articles->date.'.jpg');

              unlink($filename);
              $articles->preview_image = 1;
              $upload_valid = true;
            } else {
              Message::add('warning', '<strong>Úvodní fotografie ke článku není validní.</strong> ');
              $upload_valid = false;
            }
          }
        if ($post->check() && $upload_valid && empty($articles->published)) {

          $articles->title = $post['title'];
          $articles->seo_title = $post['seo_title'];
          $articles->text = $post['text'];
          $articles->save();

          foreach ($articles->articles_category->find_all() as $removed) {
            $articles->remove('articles_category', $removed);
          }          

          foreach ($post['categories'] as $item) {
            $articles_category = ORM::factory('articles_category', $item);
            $articles->add('articles_category', $articles_category);
            $articles_category->clear();
          }

          foreach ($articles->articles_tag->find_all() as $removed) {
            $articles->remove('articles_tag', $removed);
          }

          foreach ($post['article_tags'] as $item) {
            $model = ORM::factory('articles_tag')->where('tag', '=', $item)->find();

            if ($model->id) {
              $articles->add('articles_tag', $model);
            } else {
              $article_tags = ORM::factory('articles_tag');
              $article_tags->tag = $item;
              $article_tags->save();
              $articles->add('articles_tag', $article_tags);
              $article_tags->clear();
            }
            $articles_category->clear();
          }

          if ($articles->saved()) {
            Message::add('success', 'Článek byl upraven.');
            if (Auth::instance()->logged_in('admin')) {
              Request::instance()->redirect('administration/articles');
            } else {
              Request::instance()->redirect('articles/my');
            }
          }

        } else {

          if(empty($_POST['article_tags'] )) {
            $_POST['article_tags'] = array();
          }
          $view->set('dataPost', $_POST);
          $informations = null;

          foreach($post->errors('articles') as $item) {
            $informations .= '<span>'.$item.'</span>';
          }
          Message::add('warning', '<strong>Článek nebyl upraven.</strong> '.$informations);

          if (empty($articles->published)) {
            Message::add('warning', '<strong>Článek je publikován a nelze ho již upravovat.</strong> '.$informations);
          }
        }
      }

      $this->template->content = $view;

    }

    public function action_my() {

      $this->template->content = View::factory('templates/articles/my')
                      ->bind('articles', $articles);

      $articles = ORM::factory('article')->where('username', '=', $this->userAuth->username)->find_all();

    }

    public function action_edit($id) {

      $this->template->content = View::factory('templates/articles/edit')
              ->bind('art_cat', $art_cat)
              ->bind('articles', $articles);

      $art_cat = ORM::factory('articles_category')->find_all();
      $articles = ORM::factory('article')->where('username', '=', $this->userAuth->username)->find($id);

    }

    public function action_edit_admin($id) {

      $this->template->content = View::factory('templates/articles/edit_admin')
              ->bind('art_cat', $art_cat)
              ->bind('articles', $articles);

      $art_cat = ORM::factory('articles_category')->find_all();
      $articles = ORM::factory('article')->find($id);

    }

    public function action_delete($id) {

      if (Auth::instance()->logged_in('admin')) {
        if (ORM::factory('article')->delete($id)) {
          Message::add('success', 'Článek byl úspěšně vymazán.');
          Request::instance()->redirect('administration/articles');
        }
      } else {
        if (ORM::factory('article')->where('username', '=', $this->userAuth->username)->delete($id)) {
          Message::add('success', 'Článek byl úspěšně vymazán.');
        }
        Request::instance()->redirect('articles/my');
      }

    }


    public function action_delete_tag() {

      $articles = ORM::factory('article', $_POST['article_id']);
      $articles_tag = ORM::factory('articles_tag', $_POST['tag_id']);      
      $articles->remove('articles_tag', $articles_tag);
      $return_arr = array();
      $return_arr["check"] = 'ok';
      echo json_encode($return_arr);

    }

    public function action_publish($id) {

      $articles = ORM::factory('article', $id);      
      $articles->published = 1;
      $articles->save();
      if ($articles->saved()) {
        Message::add('success', 'Článek byl úspěšně publikován.');
        Request::instance()->redirect('administration/articles');
      } else {
        Message::add('warning', 'Článek nebyl publikován.');
        Request::instance()->redirect('administration/articles');
      }

    }

    public function action_unpublish($id) {

      $articles = ORM::factory('article', $id);
      $articles->published = null;
      $articles->save();
      if ($articles->saved()) {
        Message::add('success', 'Článek byl označen jako nepublikovaný.');
        Request::instance()->redirect('administration/articles');
      } else {
        Message::add('warning', 'Článek je stále publikován.');
        Request::instance()->redirect('administration/articles');
      }

    }

    public function after() {

      if ($this->auto_render) {
        $scripts = array('media/js/tinymce/tiny_mce.js');
        $this->template->scripts = array_reverse(array_merge($this->template->scripts, $scripts));
      }

      // Run anything that needs to run after this.
      parent::after();
    }
 } // End